package com.ksd.web.controller.system;

import com.alibaba.fastjson2.JSONObject;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.ksd.common.annotation.Log;
import com.ksd.common.config.PlayControlConfig;
import com.ksd.common.core.controller.BaseController;
import com.ksd.common.core.domain.AjaxResult;
import com.ksd.common.enums.BusinessType;
import com.ksd.common.utils.StringUtils;
import com.ksd.quartz.http.DRMHttpClient;
import com.ksd.quartz.util.TaskConstans;
import com.ksd.system.domain.SysBoard;
import com.ksd.system.domain.SysChannel;
import com.ksd.system.domain.SysChannelTemplate;
import com.ksd.system.service.ISysBoardService;
import com.ksd.system.service.ISysChannelService;
import com.ksd.system.service.ISysChannelTemplateService;
import com.ksd.system.service.ISysOperLogService;
import com.ksd.web.controller.m3beans.*;
import com.ksd.web.controller.process.ProcessVO;
import com.ksd.web.controller.service.*;
import org.aspectj.weaver.loadtime.Aj;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import java.util.*;

/**
 * 频道搜索Controller
 * 
 * @author y.wu
 * @date 2025-01-08
 */
@RestController
@RequestMapping("/system/channelSearch")
public class SysChannelSearchController extends BaseController
{

    public final Logger logger = LoggerFactory.getLogger(SysChannelSearchController.class);

    @Autowired
    private SendChannelService sendChannelService;

    @Autowired
    private ISysBoardService sysBoardService;
    @Autowired
    private ISysOperLogService sysOperLogService;

    @Autowired
    private AsyncService asyncService;
    @Autowired
    private ISysChannelTemplateService sysChannelTemplateService;
    @Autowired
    private SearchChannelService searchChannelService;
    @Autowired
    private OutputChannelService outputChannelService;
    @Autowired
    private ISysChannelService sysChannelService;
    @Autowired
    private ProcessService processService;

    /**
     * 启动一键配置任务（原接口改造：不再同步返回结果，而是返回任务ID）
     */
    @PostMapping("/clearAgainScan")
    public AjaxResult startClearAgainScan() {
        try {
            String processId = processService.createAndStartProcess();
            // 返回任务ID给前端，前端用此ID查询状态
            return AjaxResult.success("任务已启动", Collections.singletonMap("processId", processId));
        } catch (Exception e) {
            return AjaxResult.error("任务启动失败：" + e.getMessage());
        }
    }

    /**
     * 新增：查询任务状态与步骤详情（前端定时调用）
     */
    @GetMapping("/getProcessStatus")
    public AjaxResult getProcessStatus(@RequestParam("processId") String processId) {
        ProcessVO processVO = processService.getProcessStatus(processId);
        if (processVO == null) {
            return AjaxResult.error("任务不存在或已过期");
        }
        return AjaxResult.success(processVO);
    }
    /**
     * 查询网络配置列表
     */
    @PreAuthorize("@ss.hasPermi('system:channelSearch:list')")
    @GetMapping("/list")
    public AjaxResult list()
    {
        List<SysChannel> sysChannels = sysChannelService.selectSysChannelList(new SysChannel(), SysChannel.table_one);
        return success();
    }
    @PostMapping("/clearAgainScanById")
    public AjaxResult clearAgainScanById(@RequestBody SysBoard sysBoardTemp){

        logger.info("开始进行一键配置频道功能:"+sysBoardTemp.getId());
        Boolean clearChannleFlag = false;
//        SysBoard sysBoard1 = sysBoardService.selectSysBoardById(Long.valueOf(TaskConstans.boardValue1));
//        SysBoard sysBoard2 = sysBoardService.selectSysBoardById(Long.valueOf(TaskConstans.boardValue2));
        SysBoard sysBoard = sysBoardService.selectSysBoardById(sysBoardTemp.getId());
        logger.info("开始进行清除操作:"+sysBoard.getUrl()+"========="+sysBoard.getId());
        int resetResult = searchChannelService.resetProgramDbsData(sysBoard);
        logger.info("清除频道接口结果:"+resetResult);
        if (resetResult == 0) {
            logger.info("频道清除成功,开始进行循环查询");
            StartChannelScanData startChannelScanData = new StartChannelScanData();
            startChannelScanData.setBoard(sysBoard.getId().toString());
            startChannelScanData.setPolarization(3);//左旋或右旋
            startChannelScanData.setSymbolRate(28800);
            startChannelScanData.setFrequency(12020);
            int startResult = searchChannelService.startChannelScan(sysBoard, startChannelScanData);
            if (startResult == 0) {
                //开始循环搜索
                int searchResult = 1;
                do {
                    searchResult = searchChannelService.repeatedSearchM3GetService(sysBoard);
                    logger.info("searchResult:"+searchResult);
                    // 核心：每次查询后，让当前线程休眠5毫秒，降低接口访问频率
                    try {
                        Thread.sleep(3000); // 单位：毫秒，1秒=1000毫秒
                    } catch (InterruptedException e) {
                        // 若线程被中断，恢复中断状态（避免影响其他逻辑）
                        Thread.currentThread().interrupt();
                        logger.warn("直播板卡:{} 搜索循环线程被中断", sysBoard.getId(), e);
                        // 中断后可退出循环（根据业务需求，也可继续执行）
                        break;
                    }
                } while (searchResult == 1);
                logger.info("最后一次查询结果:"+searchResult);
                if (searchResult == 0) {
                    logger.info("频道搜索完成,停止查询,执行stop接口");
                    //停止查询==>获取最新频道
                    int stopResult = searchChannelService.stopChannelScan(sysBoard);
                    if (stopResult == 0) {
                        clearChannleFlag = true;
                    }
                }else{
                    //最后的搜索结果,也可能是2或者-1
                    searchChannelService.stopChannelScan(sysBoard);
                    logger.error("直播板卡:"+sysBoard.getId()+" 频道搜索失败,请检查网络连接."+sysBoard.getUrl());
                }
            }else{
                logger.error("直播板卡:"+sysBoard.getId()+" 频道开始进行频道搜索失败,请检查网络连接."+sysBoard.getUrl());
            }
        }else{
            logger.error("清除直播板卡:"+sysBoard.getId()+" 频道失败,请检查网络连接."+sysBoard.getUrl());
        }
        logger.info("直播板卡的频道是否重新洗牌成功:"+clearChannleFlag);

        if (clearChannleFlag) {
            //两个频道都已进行清除,并重新搜索完毕,现需要重新分发默认频道
            AjaxResult ajaxResult = setSysChannleUpdate(sysBoard);
            return ajaxResult;
        }else {
            logger.error("直播板卡"+sysBoard.getId()+"的频道搜索失败,已停止搜索,且重新获取该板卡最新分配到的最新频道");

//            QueryInfo queryInfo = new QueryInfo();
//            queryInfo.setBoard(sysBoard.getId().toString());
//            int getPrfDataListResult = outputChannelService.getPrfDataList(sysBoard, queryInfo);
            //前面已经将频道置空
            return AjaxResult.error("直播板卡"+sysBoard.getId()+"的频道搜索失败,已停止搜索");
//            Long id = sysBoardTemp.getId();
//            if (id == Long.valueOf(TaskConstans.boardValue1) ){
//                //没有洗牌成功==>重新获取之前的频道信息
//                //将直播板卡1之前已配置的频道数据清空
//                SysChannelTemplate sysChannelTemplate = new SysChannelTemplate();
//                sysChannelTemplate.setStatus(TaskConstans.status_selected);
//                sysChannelTemplate.setBoardId(Long.valueOf(TaskConstans.boardValue1));
//                List<SysChannelTemplate> sysChannelTemplates = sysChannelTemplateService.selectSysChannelTemplateListByChannelId(sysChannelTemplate);
//                logger.info("频道标准里直播板卡1之前配置的频道个数:"+sysChannelTemplates.size());
//                for (SysChannelTemplate channelTemplate : sysChannelTemplates) {
//                    channelTemplate.setStatus(TaskConstans.status_init);
//                    sysChannelTemplateService.updateSysChannelTemplate(channelTemplate);
//                }
//                List<SysChannel> sysChannels = sysChannelService.selectSysChannelListByOrStatus(TaskConstans.status_selected, TaskConstans.status_selected, SysChannel.table_one);
//                logger.info("直播板卡1之前配置的频道个数=========:"+sysChannels.size());
//                for (SysChannel sysChannel : sysChannels) {
//                    sysChannel.setStatus1(TaskConstans.status_init);
//                    sysChannel.setStatus2(TaskConstans.status_init);
//                    sysChannelService.updateSysChannel(sysChannel,SysChannel.table_one);
//                }
//            }else if(id == Long.valueOf(TaskConstans.boardValue2)) {
//                //没有洗牌成功
//                //将直播板卡2之前配置的频道数据清空
//                SysChannelTemplate sysChannelTemplate = new SysChannelTemplate();
//                sysChannelTemplate.setStatus(TaskConstans.status_selected);
//                sysChannelTemplate.setBoardId(Long.valueOf(TaskConstans.boardValue2));
//                List<SysChannelTemplate> sysChannelTemplates = sysChannelTemplateService.selectSysChannelTemplateListByChannelId(sysChannelTemplate);
//                logger.info("频道标准表里直播板卡2之前配置的频道个数:"+sysChannelTemplates.size());
//                for (SysChannelTemplate channelTemplate : sysChannelTemplates) {
//                    channelTemplate.setStatus(TaskConstans.status_init);
//                    sysChannelTemplateService.updateSysChannelTemplate(channelTemplate);
//                }
//                List<SysChannel> sysChannels = sysChannelService.selectSysChannelListByOrStatus(TaskConstans.status_selected, TaskConstans.status_selected, SysChannel.table_twice);
//                logger.info("直播板卡2之前配置的频道个数=========:"+sysChannels.size());
//                for (SysChannel sysChannel : sysChannels) {
//                    sysChannel.setStatus1(TaskConstans.status_init);
//                    sysChannel.setStatus2(TaskConstans.status_init);
//                    sysChannelService.updateSysChannel(sysChannel,SysChannel.table_twice);
//                }
//            }
//            return error("设置直播板卡:"+sysBoard.getId()+"进行频道搜索失败，请检查网络连接."+sysBoard.getUrl());
        }



    }

    public AjaxResult setSysChannleUpdate(SysBoard sysBoard) {
        logger.info("开始进行默认分发频道设置:"+sysBoard.getUrl());
        //在停止查询接口会进行频道搜索,会将所有频道重新插入数据库中,等待1秒
        //查询频道表是否有数据,如果有数据,开始进行频道默认分发处理
        List<SysChannel> sysChannels = new ArrayList<>();
        if (TaskConstans.boardValue1.equals(sysBoard.getId().toString())) {
            logger.info("直播板卡1");
            sysChannels = sysChannelService.selectSysChannelList(new SysChannel(), SysChannel.table_one);
            logger.info("个数:"+sysChannels.size());
        }else if(TaskConstans.boardValue2.equals(sysBoard.getId().toString())) {
            logger.info("直播板卡2");
            sysChannels = sysChannelService.selectSysChannelList(new SysChannel(), SysChannel.table_twice);
            logger.info("size:"+sysChannels.size());
        }
        logger.info("查询到的最新频道列表数据个数:"+sysChannels.size()+"============直播板卡id:"+sysBoard.getId());
        if (sysChannels.size() != 0) {
            logger.info("开始进行直播板卡:" + sysBoard.getId() + " 的节目分发");
            SysChannelTemplate sysChannelTemplate = new SysChannelTemplate();
            sysChannelTemplate.setPush(sysBoard.getId());
            List<SysChannelTemplate> sysChannelTemplates = sysChannelTemplateService.selectSysChannelTemplateList(sysChannelTemplate);
            logger.info("该直播板卡设置的默认配置的频道个数:" + sysChannelTemplates.size());
            //进行默认分发
            DeliveryParamObject deliveryParamObject = new DeliveryParamObject();
            deliveryParamObject.setBordId(sysBoard.getId().toString());
            Set<String> freqs = new HashSet<>();
            List<SysChannel> selectedChannels = new ArrayList<>();


            List<SaveServiceInfo> saveServiceInfoList = new ArrayList<>();
            for (SysChannelTemplate channelTemplate : sysChannelTemplates) {
                String name = channelTemplate.getName();
                SysChannel sysChannel = new SysChannel();
                if (TaskConstans.boardValue1.equals(sysBoard.getId().toString())) {
                    sysChannel = sysChannelService.selectSysChannelByName(name, SysChannel.table_one);
                } else if (TaskConstans.boardValue2.equals(sysBoard.getId().toString())) {
                    sysChannel = sysChannelService.selectSysChannelByName(name, SysChannel.table_twice);
                }
                if (sysChannel != null) {
                    selectedChannels.add(sysChannel);//默认选中的分发频道
                    logger.info("选中默认配置的频道有:" + sysChannel.getName() + "=====频道表:" + sysChannel.getId() + "==============" + sysChannel.getFreq());
                    //默认分发频道有限制,当前默认分发频道个数为不允许超过6个
                    freqs.add(sysChannel.getFreq().toString());
                }
            }

            //重新针对各个高频头选择默认分发
            List<SysChannel> selectedChannelsCountList = new ArrayList<>();
            for (String everyFreq : freqs) {
                //有2个高频头,平均每个分配2个频道
                int count = 0;
                for (SysChannel selectedChannel : selectedChannels) {
                    Long freq = selectedChannel.getFreq();
//                    if (everyFreq.equals(freq.toString()) && count < Long.valueOf(PlayControlConfig.getSelectSysChannelSingleCount())) {
                    if (everyFreq.equals(freq.toString())) {
                        selectedChannelsCountList.add(selectedChannel);
                        count ++;
                    }
                }
            }
            logger.info("设置默认分发频道个数:" + selectedChannels.size() + ",频率freqs size:" + freqs.size());
            selectedChannels = new ArrayList<>();
            for (SysChannel sysChannel : selectedChannelsCountList) {
                selectedChannels.add(sysChannel);
            }
            logger.info("重新根据当前直播板卡每次最多允许配置频道个数,设置默认分发频道个数:" + selectedChannels.size() + ",频率freqs size:" + freqs.size());
            List<DeliveryParam> deliveryParam = new ArrayList<>();
            for (String freq : freqs) {
                DeliveryParam delivery = new DeliveryParam();
                delivery.setSymbolRate(28800);
                delivery.setPolarization(3);
                delivery.setFrequency(Integer.valueOf(freq));
                deliveryParam.add(delivery);
            }
            deliveryParamObject.setDeliveryParam(deliveryParam);

            int mainFreqExResult = outputChannelService.setMainFreqEx(sysBoard, deliveryParamObject);
            logger.info("==========开始进行设置默认分发频道,setMainFreqEx接口结果:" + mainFreqExResult);
            if (mainFreqExResult == 0) {

                for (String freq : freqs) {
                    List<SaveService> serviceInfoObjectList = new ArrayList<>();
                    Long onid = 0L;
                    Long tsid = 0L;
                    Long symbolRate = 0L;
                    SaveServiceInfo saveServiceInfo = new SaveServiceInfo();
                    for (int i = 0; i < selectedChannels.size(); i++) {
                        SysChannel selectedChannel = selectedChannels.get(i);
                        Long freqResult = selectedChannel.getFreq();
                        if (freq.equals(freqResult.toString())) {
//                            logger.info("freqResult:" + freqResult);
                            logger.info("freqResult:" + freqResult+",默认选中:" + selectedChannel.getName());
                            onid = selectedChannel.getOnid();
                            tsid = selectedChannel.getTsid();
//                            logger.info(onid + "===================tsId:" + tsid);
//                                                symbolRate = selectedChannel.getSymbolRate();
                            SaveService serviceInfoObject = new SaveService();
                            serviceInfoObject.setId(Integer.valueOf(selectedChannel.getPmtpid().toString()));
                            serviceInfoObject.setName(selectedChannel.getName());
                            serviceInfoObject.setProtocol("udp");
                            serviceInfoObject.setIp(selectedChannel.getIp());
                            serviceInfoObject.setPort(Integer.valueOf(selectedChannel.getPort()));
                            serviceInfoObject.setUrl("");
                            serviceInfoObjectList.add(serviceInfoObject);
                        }
                    }
                    logger.info("saveServiceList:" + serviceInfoObjectList.size());
                    saveServiceInfo.setServiceinfo(serviceInfoObjectList);
                    saveServiceInfo.setOnid(Integer.valueOf(onid.toString()));
                    saveServiceInfo.setTsid(Integer.valueOf(tsid.toString()));
//                                        saveServiceInfo.setFrequency(Integer.valueOf(freq.toString()));
//                                        saveServiceInfo.setSymbolRate(Integer.valueOf(symbolRate.toString()));
                    saveServiceInfoList.add(saveServiceInfo);
                }
                //开始进行保存
                SaveSatelliteInfo saveSatelliteInfo = new SaveSatelliteInfo();
                saveSatelliteInfo.setBoard(sysBoard.getId().toString());
                saveSatelliteInfo.setSatellite("1");//1表示高频头1  2表示高频头2
                saveSatelliteInfo.setServiceInfo(saveServiceInfoList);
                logger.info("开始设置重新分发默认频道");
                AjaxResult ajaxResult = outputChannelService.setPrfDataSave(sysBoard, saveSatelliteInfo);
                logger.info("======保存频道结果========:" + ajaxResult.toString());
                if (ajaxResult != null && ajaxResult.isSuccess()) {
                    //开始获取最新频道
                    QueryInfo queryInfo = new QueryInfo();
                    queryInfo.setBoard(sysBoard.getId().toString());
                    int getPrfDataListResult = outputChannelService.getPrfDataList(sysBoard, queryInfo);
                    logger.info("设置默认分发频道结果:" + getPrfDataListResult);
                    if (getPrfDataListResult == 0) {
                        logger.info("===================重置分发频道成功===========================");
                        return success();
                    }else{
                        return error("保存设置直播板卡:"+sysBoard.getId()+"默认分发频道失败，请检查网络连接");
                    }
                }
                logger.info("直播板卡:" + sysBoard.getId() + " ,设置默认分发频道结束:" + sysBoard.getUrl());
                return ajaxResult;
            }
        }
        return error("设置直播板卡:"+sysBoard.getId()+"默认分发频道失败，请检查网络连接");
    }
    @PostMapping("/startChannelScanData")
    public AjaxResult startChannelScanData(@RequestBody StartChannelScanData startChannelScanData)
    {
        logger.info("startChannelScanData=================="+startChannelScanData.toString());
        logger.info(startChannelScanData.toString());
        String board = startChannelScanData.getBoard();
        String url = "";
        if (TaskConstans.boardValue1.equals(board)){
            SysBoard sysBoard = sysBoardService.selectSysBoardById(Long.valueOf(board));
            url = sysBoard.getUrl();
        }else if (TaskConstans.boardValue2.equals(board)){
            SysBoard sysBoard = sysBoardService.selectSysBoardById(Long.valueOf(board));
            url = sysBoard.getUrl();
        }
        StartChannelParameter startChannelParameter = new StartChannelParameter();
        startChannelParameter.setScanType(1);
        TuningParameter tuningParameter = new TuningParameter();
        tuningParameter.setFrequency(startChannelScanData.getFrequency());
        tuningParameter.setSymbolRate(startChannelScanData.getSymbolRate());
        tuningParameter.setPolarization(startChannelScanData.getPolarization());
        List<TuningParameter> list = new ArrayList<>();
        list.add(tuningParameter);
        startChannelParameter.setTuningParameters(list);
        String response = sendChannelService.startChannelScan(startChannelParameter,url);
        sysOperLogService.insertOperlogApiSuccess("频道搜索开始接口.请求地址: "+url+",响应数据:"+response);
        if (StringUtils.isEmpty(response)){
            sysOperLogService.insertOperlogApiError("频道搜索开始.请求地址: "+url+",接口响应超时,请检查网络连接或联系管理员稍后重试");
            return error("频道搜索开始接口响应超时,请检查网络连接或联系管理员稍后重试");
        }
        ObjectMapper mapperPage = new ObjectMapper();
        StartChannelScanResponse startChannelScanResponse = null;
        try {
            ObjectMapper objectMapper = new ObjectMapper();
            // 将 JSON 字符串解析为 JsonNode 对象
            JsonNode rootNode = objectMapper.readTree(response);
            // 获取 status 节点的值
            int statusInt = rootNode.get("status").asInt();
            if (statusInt != 0) {
                sysOperLogService.insertOperlogApiError("频道搜索开始接口.请求地址: "+url+",响应状态失败，请联系管理员检查接口服务或稍后重试");
                return error("频道搜索开始接口响应状态失败，请联系管理员检查接口服务或稍后重试");
            } else if (statusInt == 0) {
                return success(url);
            }
        } catch (JsonProcessingException e) {
            throw new RuntimeException(e);
        }
        return error();
    }

    @PostMapping("/stopChannelScanData")
    public AjaxResult stopChannelScanData(@RequestBody StopChannelScanData stopChannelScanData)
    {
        logger.info("停止搜索============================"+stopChannelScanData.toString());
        String board = stopChannelScanData.getBoard();
        String url = "";
        if (TaskConstans.boardValue1.equals(board)){
            SysBoard sysBoard = sysBoardService.selectSysBoardById(Long.valueOf(board));
            url = sysBoard.getUrl();
        }else if (TaskConstans.boardValue2.equals(board)){
            SysBoard sysBoard = sysBoardService.selectSysBoardById(Long.valueOf(board));
            url = sysBoard.getUrl();
        }
        String response = sendChannelService.stopChannelScan(url);
        sysOperLogService.insertOperlogApiSuccess("频道搜索结束接口.请求地址: "+url+",响应数据:"+response);
        if (StringUtils.isEmpty(response)){
            sysOperLogService.insertOperlogApiError("频道搜索结束接口.请求地址: "+url+",响应超时,请检查网络连接或联系管理员稍后重试");
            return error("频道搜索结束接口响应超时,请检查网络连接或联系管理员稍后重试");
        }
        ObjectMapper mapperPage = new ObjectMapper();
        StopChannelScanResponse stopChannelScanResponse = null;
        try {
            ObjectMapper objectMapper = new ObjectMapper();
            // 将 JSON 字符串解析为 JsonNode 对象
            JsonNode rootNode = objectMapper.readTree(response);
            // 获取 status 节点的值
            int statusInt = rootNode.get("status").asInt();
            logger.info("搜索结束接口响应状态:"+statusInt);
            if (statusInt != 0) {
                sysOperLogService.insertOperlogApiError("频道搜索结束接口.请求地址: "+url+",响应状态失败，请联系管理员检查接口服务或稍后重试");
                return error("频道搜索结束接口响应状态失败，请联系管理员检查接口服务或稍后重试");
            } else if (statusInt == 0) {
                stopChannelScanResponse = mapperPage.readValue(response, StopChannelScanResponse.class);
                logger.info("搜索结束接口响应数据:"+stopChannelScanResponse.toString());
                asyncService.sendChannelListManageDataAsync(Long.valueOf(board));
                return success();
            }
        } catch (JsonProcessingException e) {
            throw new RuntimeException(e);
        }
        return success();
    }

    //清除频道
    @PostMapping("/resetProgramDbsData")
    public AjaxResult resetProgramDbsData(@RequestBody ResetProgramData resetProgramData)
    {
        logger.info(resetProgramData.toString());

        String board = resetProgramData.getBoard();
        String url = "";
        if (TaskConstans.boardValue1.equals(board)){
            SysBoard sysBoard = sysBoardService.selectSysBoardById(Long.valueOf(board));
            url = sysBoard.getUrl();
        }else if (TaskConstans.boardValue2.equals(board)){
            SysBoard sysBoard = sysBoardService.selectSysBoardById(Long.valueOf(board));
            url = sysBoard.getUrl();
        }
        String response = sendChannelService.resetProgramService(url);
        sysOperLogService.insertOperlogApiSuccess("频道清除接口.请求地址: "+url+",响应数据:"+response);
        if (StringUtils.isEmpty(response)){
            sysOperLogService.insertOperlogApiError("频道清除接口.请求地址: "+url+",响应超时,请检查网络连接或联系管理员稍后重试");
            return error("频道清除接口响应超时,请检查网络连接或联系管理员稍后重试");
        }
        ObjectMapper mapperPage = new ObjectMapper();
        StopChannelScanResponse stopChannelScanResponse = null;
        try {
            ObjectMapper objectMapper = new ObjectMapper();
            // 将 JSON 字符串解析为 JsonNode 对象
            JsonNode rootNode = objectMapper.readTree(response);
            // 获取 status 节点的值
            int statusInt = rootNode.get("status").asInt();
            if (statusInt != 0) {
                sysOperLogService.insertOperlogApiError("频道清除接口.请求地址: "+url+",响应状态失败，请联系管理员检查接口服务或稍后重试");
                return error("频道清除接口响应状态失败，请联系管理员检查接口服务或稍后重试");
            } else if (statusInt == 0) {
                stopChannelScanResponse = mapperPage.readValue(response, StopChannelScanResponse.class);
                //清除完成之后,需要将对应的频道删除
                //清空已配置的频道
                SysChannelTemplate sysChannelTemplate = new SysChannelTemplate();
                sysChannelTemplate.setBoardId(Long.valueOf(board));
                sysChannelTemplate.setStatus(TaskConstans.status_selected);
                List<SysChannelTemplate> sysChannelTemplates = sysChannelTemplateService.selectSysChannelTemplateList(sysChannelTemplate);
                for (SysChannelTemplate channelTemplate : sysChannelTemplates) {
                    channelTemplate.setStatus(TaskConstans.status_init);
                    sysChannelTemplateService.updateSysChannelTemplate(channelTemplate);
                }
                return success(stopChannelScanResponse);
            }
        } catch (JsonProcessingException e) {
            throw new RuntimeException(e);
        }
        return error();
    }

    @PostMapping("/resetSetPrfData")
    public AjaxResult resetSetPrfData(@RequestBody ResetProgramData resetProgramData){
        logger.info(resetProgramData.toString());
        String board = resetProgramData.getBoard();
        String url = "";
        if (TaskConstans.boardValue1.equals(board)){
            SysBoard sysBoard = sysBoardService.selectSysBoardById(Long.valueOf(board));
            url = sysBoard.getUrl();
        }else if (TaskConstans.boardValue2.equals(board)){
            SysBoard sysBoard = sysBoardService.selectSysBoardById(Long.valueOf(board));
            url = sysBoard.getUrl();
        }
        String response = sendChannelService.resetSetPrfDataService(url);
        sysOperLogService.insertOperlogApiSuccess("频道清除设置接口.请求地址: "+url+",响应数据:"+response);
        if (StringUtils.isEmpty(response)){
            sysOperLogService.insertOperlogApiError("频道清除设置接口.请求地址: "+url+",响应超时,请检查网络连接或联系管理员稍后重试");
            return error("频道清除设置接口响应超时,请检查网络连接或联系管理员稍后重试");
        }
        ObjectMapper mapperPage = new ObjectMapper();
        StopChannelScanResponse stopChannelScanResponse = null;
        try {
            ObjectMapper objectMapper = new ObjectMapper();
            // 将 JSON 字符串解析为 JsonNode 对象
            JsonNode rootNode = objectMapper.readTree(response);
            // 获取 status 节点的值
            int statusInt = rootNode.get("status").asInt();
            if (statusInt != 0) {
                sysOperLogService.insertOperlogApiError("频道清除设置接口.请求地址: "+url+",响应状态失败，请联系管理员检查接口服务或稍后重试");
                return error("频道清除设置接口响应状态失败，请联系管理员检查接口服务或稍后重试");
            } else if (statusInt == 0) {
                stopChannelScanResponse = mapperPage.readValue(response, StopChannelScanResponse.class);


                return success(stopChannelScanResponse);
            }
        } catch (JsonProcessingException e) {
            throw new RuntimeException(e);
        }

        return success();
    }
    /**
     * 搜索频道
     */
    @PreAuthorize("@ss.hasPermi('system:channelSearch:edit')")
    @Log(title = "频道搜索", businessType = BusinessType.UPDATE)
    @PostMapping("/m3GetService")
    public AjaxResult m3GetService(@RequestBody M3Bean m3Bean)
    {
        return searchM3Service(m3Bean);
    }
    public AjaxResult searchM3Service(M3Bean m3Bean){
        String url = m3Bean.getUrl();
        logger.info("进行频道循环搜索=================="+m3Bean.toString());
        M3Request m3RequestInfo = M3Request.getM3RequestInfo(TaskConstans.getServiceInfo);
        String jsonString = JSONObject.toJSONString(m3RequestInfo);
        logger.info("[system-channelSearch] The search M3 task get url :" + url);
        logger.info("[system-channelSearch] The search M3 task get request :" + jsonString);

        String response = DRMHttpClient.udrmHttpDoGet(url, jsonString);
        sysOperLogService.insertOperlogApiSuccess("频道搜索接口.请求地址: "+url+",响应数据:"+response);
        if (StringUtils.isEmpty(response)){
            sysOperLogService.insertOperlogApiError("频道搜索接口.请求地址: "+url+",响应超时,请检查网络连接或连接管理员稍后重试");
            return error("频道搜索接口响应超时,请检查网络连接或联系管理员稍后重试");
        }
        ObjectMapper objectMapper = new ObjectMapper();
        JsonNode jsonNode = null;
        try {
            jsonNode = objectMapper.readTree(response);
        } catch (JsonProcessingException e) {
            logger.error(e.getMessage());
            throw new RuntimeException(e);
        }
        int status = jsonNode.get("status").asInt();
        logger.info("搜索结果状态:"+status);
        if (status == 2) {
            sysOperLogService.insertOperlogApiError("搜索频道接口.请求地址: "+url+",响应状态失败，请联系管理员检查接口服务或稍后重试");
            return success(status);
        }else if(status == 0){
            sysOperLogService.insertOperlogApiSuccess("搜索频道接口.请求地址: "+url+",搜索完成");
            //如果状态为0,停止查询,执行stop接口
            return success(status);
        }else if(status == 1){
            //如果状态为1,持续查询
            return success(status);
        }else{
            return success(status);
        }
    }

}
